from flask import Blueprint, render_template, redirect, url_for, session, flash, jsonify, g
from flask import request
from exts import db, mail
from models import UserModel,MemberModel
from decorators import login_req, login_required
bp = Blueprint("member", __name__, url_prefix="/member")


@bp.route("/", methods=['GET'])
@login_required
def members():
    members = MemberModel.query.all()
    result = []
    for member in members:
        member_data = {
            'id': member.id,
            'points': member.points,
            'mobile': member.mobile,
            'name': member.name
        }
        result.append(member_data)
    return render_template("会员管理.html", members=result)



@bp.route("/manage", methods=['POST'])
@login_required
def manage_member():
    member_id = request.form['member_id']
    new_points = int(request.form['new_points'])
    new_mobile = request.form['new_mobile']
    new_name = request.form['new_name']
    member = MemberModel.query.get(member_id)

    if member:
        if (member.points-new_points)<0:
            flash('积分不能小于0', 'error')
            return redirect(url_for('member.members'))
        member.points = member.points-new_points
        member.mobile = new_mobile
        member.name = new_name
        db.session.commit()
        flash('会员信息更新成功', 'success')
    else:
        flash('会员不存在', 'error')
    return redirect(url_for('member.members'))

@bp.route("/delete", methods=['POST'])
@login_required
def delete_member():
    member_id = request.form['member_id']

    member = MemberModel.query.get(member_id)
    if member:
        db.session.delete(member)
        db.session.commit()
        flash('会员删除成功', 'success')
    else:
        flash('会员不存在', 'error')

    return redirect(url_for('member.members'))

@bp.route('/add_member', methods=['POST'])
def add_member():
    points = int(request.form['points'])
    mobile = request.form['mobile']
    name = request.form['name']

    member = MemberModel(points=points, mobile=mobile, name=name)
    db.session.add(member)
    db.session.commit()

    return redirect(url_for('member.members'))

@bp.route('/search_members', methods=['GET'])
def search_members():
    search_text = request.args.get('search')  # 获取查询字符串中的搜索关键字
    if search_text:
        members = MemberModel.query.filter(
            (MemberModel.name.ilike(f"%{search_text}%")) |
            (MemberModel.mobile.ilike(f"%{search_text}%"))
        ).all()
    else:
        members = MemberModel.query.all()

    result = []
    for member in members:
        member_data = {
            'id': member.id,
            'points': member.points,
            'mobile': member.mobile,
            'name': member.name
        }
        result.append(member_data)
    return render_template("会员管理.html", members=result)